<%@ Page Language="C#" autoeventwireup="true"  %>
<%@ Import Namespace="SoftwareMonkeys.Scriptech.Web" %>
<%@ Import Namespace="SoftwareMonkeys.Scriptech.Diagnostics" %>
<script runat="server">
		public string ErrorMessage = String.Empty;
		public string ReferringScript = String.Empty;

		private void Page_Load (object sender, EventArgs e)
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Loading error page."))
			{
				try
				{
					Exception ex = Server.GetLastError();
					
					ReferringScript = Request.QueryString["ReferringScript"];
					
					LogWriter.Debug("Referring script: " + ReferringScript);
					
					if (ex != null)
						ErrorMessage = GetErrorMessage(ex);
					else
						ErrorMessage = "No error has occurred.";
					
					LogWriter.Debug("Error message: " + ErrorMessage);
				
					DataBind();
				}
				catch (Exception ex)
				{
					LogWriter.Error(ex);
				}
			}
		}
		
		private string GetEditUrl()
		{
			string url = String.Empty;
		
			using (LogGroup logGroup = LogGroup.StartDebug("Creating the URL to edit the problematic script."))
			{
				string editPage = WebUtilities.MapUrlPath("/EditScript.aspx");
				
				string queryStrings = "?Script=" + ReferringScript;
				
				queryStrings = queryStrings + GetExistingQueryStrings();
				
				url = editPage + queryStrings;
				
				LogWriter.Debug("URL: " + url);
			}
			return url;
		}
		
		private string GetExistingQueryStrings()
		{
			string queryStrings = String.Empty;
						
			string originalQueryStrings = Request.Url.Query;
						
			if (originalQueryStrings.IndexOf("&") > -1)
			{
				queryStrings = originalQueryStrings.Substring(originalQueryStrings.IndexOf("&")+1,
					originalQueryStrings.Length-originalQueryStrings.IndexOf("&") - 1);
			}
			
			if (queryStrings != String.Empty)
				queryStrings = "&" + queryStrings;
			
			return queryStrings;
		}
		
		private string GetErrorMessage(Exception exception)
		{
			string msg = String.Empty;
			Exception tmpEx = exception;
			
			while (tmpEx != null)
			{
				msg = msg + "\n" + tmpEx.ToString();
				tmpEx = tmpEx.InnerException;
			}
			
			return msg;
		}
		
		private string OutputStyle()
		{
			return "<link href='" + WebUtilities.ConvertApplicationRelativeUrlToAbsoluteUrl("/Content/site.css") + "' rel='stylesheet' type='text/css' />";
		}
</script>
<html>
<head>
<title>Error</title>
<%= OutputStyle() %>
</head>
<body>
<h1>Oops...</h1>
<p>
<a href='<%= WebUtilities.MapUrlPath("/") %>'>&laquo; Home</a>
</p>

<textarea style="width: 100%; height: 500px;"><%= ErrorMessage != null ? ErrorMessage : String.Empty %></textarea>
<% if (ReferringScript != "Not found"){ %>
<p>
	Faulty script: <%= ReferringScript %>
</p>
<p>
	<a href='<%= GetEditUrl() %>'>Edit faulty script &raquo;</a>
</p>
<% } %>
<p>
	<a href='javascript:history.go(-1);'>&laquo; Back (Previous Page)</a>
</p>
<p>
	
</p>
</body>
</html>